/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, TimePicker2 } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, DATE_TEXT, TIME_TEXT } from '../stores/definitions_set';
import moment from 'moment';

const FromItem = Form.Item;

const ShiftTimeForm = ({
  visible,
  modal,
  onSubmit,
  onCancel,
  shiftsInfo,
}) => {
  // eslint-disable-next-line no-unused-vars
  const { scShareStore: store } = useStore();
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [share] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    const { shiftDate, shiftTime } = shiftsInfo || {};
    _.assign(share, {
      shiftDate,
      shiftTime,
      shiftCode: shiftsInfo?.id,
    });
    editCtx.origin = _.cloneDeep({});
    // 添加操作,设置默认值
    return () => {
      _.assign(share, {
        shiftDate: '',
        shiftTime: '',
        shiftCode: '',
      });
    };
  }, [visible]);

  if (!share) return <></>;
  const now = moment(); // 获取当前时间 Moment 对象

  const overrideModel = {
    shiftTime: {
      label: t`班次时间`,
      ui: {
        renderer: (v) => (
          <TimePicker2
            placeholder="请选择"
            value={v}
            format="HH:mm"
            // disabledHours={(data) => data < now.hour()}
            // disabledMinutes={(data) => {
            //   const selectHour = v.split(':')[0];
            //   if (Number(selectHour) == now.hour()) {
            //     return data < now.minute();
            //   } else if (Number(selectHour) < now.hour()) {
            //     return true;
            //   }
            // }}
          />
        ),
        itemProps: { required: true },
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(share, name, value);
    if (name === 'shiftDate') {
      _.set(share, 'shiftDate', DATE_TEXT(value));
    }
    if (name === 'shiftTime') {
      _.set(share, 'shiftTime', TIME_TEXT(value));
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(share);
  };

  return (
    <>
      <Dialog
        visible={!!visible}
        onCancel={handleCancel}
        onClose={handleCancel}
        title={t`编辑班次时间`}
        style={{ width: '30%' }}
        footer={null}
      >
        <Form
          isPreview={isViewMode}
          {...formProps}
          value={share}
          colon
          onChange={handleChange}
          useLabelForErrorMessage
        >
          <FieldsGrid
            formData={share}
            mode={modal[0]}
            columns={1}
            overrideModel={overrideModel}
            fields={['shiftDate', 'shiftTime', 'warn']}
          />
          <DrawerFooter>
            <FromItem>
              {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
              <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
            </FromItem>
          </DrawerFooter>
        </Form>
      </Dialog>
    </>
  );
};

export default observer(ShiftTimeForm);
